package com.xiaoqiudong.forum.service.impl;

import com.xiaoqiudong.forum.common.AppResult;
import com.xiaoqiudong.forum.common.ResultCode;
import com.xiaoqiudong.forum.common.utils.MD5Util;
import com.xiaoqiudong.forum.common.utils.StringUtils;
import com.xiaoqiudong.forum.common.utils.UUIDUtils;
import com.xiaoqiudong.forum.dao.UserMapper;
import com.xiaoqiudong.forum.exception.ApplicationException;
import com.xiaoqiudong.forum.model.User;
import com.xiaoqiudong.forum.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-23
 * Time:10:07
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        if (user == null){
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_IS_NULL));
        }
        //检查用户是否存在
        User existUser = userMapper.selectByUserName(user.getUsername());
        if (existUser != null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString()+" username = " +user.getUsername());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
        }
        if (user.getGender() == null){
            user.setGender((byte) 2);
        }
        //填充默认值
        user.setIsAdmin((byte) 0);
        user.setAvatarUrl(null);
        user.setArticleCount(0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insertSelective(user);
        if (row != 1){
            log.info(ResultCode.FAILED_CREATE.toString()+"username= "+ user.getUsername());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功：username = " + user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        if(StringUtils.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByUserName(username);
        return user;
    }

    @Override
    public User login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //按用户名查询消息
        User user = selectByUserName(username);
        if (user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        String encryptPassword = MD5Util.md5Salt(password,user.getSalt());
        if (!encryptPassword.equalsIgnoreCase(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }

        //登录成功
        log.info("登录成功，username= "+ username);
        return user;
    }

    @Override
    public User selectById(Long id) {
        if(id == null || id <= 0){
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_LOGIN));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"user id ="+id);
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"user id ="+id);
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if (updateUser.getArticleCount() < 0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.FAILED.toString() + ", 受影响的行数不等于 1 .");
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //1.非空检验
        if (user == null || user.getId() == null || user.getId() <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        //2.检验用户是否存在
        User exitUser = userMapper.selectByPrimaryKey(user.getId());
        if (exitUser == null ){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 3.定义一个标志为位,检测是否需要修改
        boolean checkAttr = false; // false 表示不需要修改
        // 4. 定义一个专门用来更新的对象，防止用户传入的User对象设置了其他的属性
        // 当使用动态SQL进行更新的时候，覆盖了没有经过校验的字段

        User updateUser = new User();

        // 5. 设置用户id
        updateUser.setId(user.getId());

        //6.对每个校验位检测
        if (!StringUtils.isEmpty(user.getUsername())
                && !user.getUsername().equals(exitUser.getUsername()) ){
            // 需要更新用户名(登录名)时，进行唯一性的校验
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if (checkUser != null){
                //用户已存在
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        //7.校验昵称
        if(!StringUtils.isEmpty(user.getNickname())
                && !user.getNickname().equals(exitUser.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        //8. 检测性别
        if (user.getGender() != null && user.getGender() != exitUser.getGender()){
            updateUser.setGender(user.getGender());
            if (updateUser.getGender()>2 || updateUser.getGender() < 0){
                updateUser.setGender((byte) 2);
            }
            checkAttr = true;
        }
        //9.检测邮箱
        if (!StringUtils.isEmpty(user.getEmail())
                && !user.getEmail().equals(exitUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }
        // 10.检验电话号码
        if(!StringUtils.isEmpty(user.getPhoneNum())
                && !user.getPhoneNum().equals(exitUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        // 11.个人简介
        if (!StringUtils.isEmpty(user.getRemark())
                && !user.getRemark().equals(exitUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }
        // 根据标志位来检测是否更新
        if(checkAttr == false){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //检验密码是否正确
        String oldEntryPassword = MD5Util.md5Salt(oldPassword,user.getSalt());
        if (!user.getPassword().equalsIgnoreCase(oldEntryPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生成新盐值
        String salt = UUIDUtils.UUID_32();
        //生成新密码
        String newEncryptPassword = MD5Util.md5Salt(newPassword,salt);

        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(newEncryptPassword);

        //更新密码
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }
}
